package com.smartwork.common.mobile.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import com.smartwork.common.mobile.web.BaseController;
import com.smartwork.common.mobile.wechat.constant.StaticValue;
import com.smartwork.common.mobile.wechat.service.TokenService;
import com.smartwork.common.mobile.wechat.thread.JsapiTicketThread;
import com.smartwork.common.mobile.wechat.util.JsApiSign;
import com.smartwork.common.mobile.wechat.util.WeixinConfUtils;
import com.smartwork.common.mobile.wechat.util.WeixinUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/wechat")
public class WeixinController extends BaseController{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Resource(name = "tokenService")
	private TokenService tokenService;

	@RequestMapping(value = "/oauth")
	@ResponseBody
	public Map<String, Object> doOAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter("code");
        String o = request.getParameter("o");
		String redirect_uri = request.getParameter("redirect_uri");
		Map<String, Object> responseMap = new HashMap<String, Object>();
		logger.info("redirect_uri==>" + redirect_uri);
		if (null == code || "".equals(code)) {
			String state = "state";
			String url = String.format(StaticValue.oAuthCodeUrl, WeixinConfUtils.getValue(o, "appID"),
                    URLEncoder.encode(redirect_uri, "utf-8"), state);
			responseMap.put("send", url);
			responseMap.put("cd", "0");
			return responseMap;
		} else {
			JSONObject tokenJson = tokenService.getOAuthToken(o, code);
			String url = String.format(StaticValue.oAuthFetchUserMsgUrl,
                    tokenJson.getString("access_token"), tokenJson.getString("openid"));
			JSONObject userJson = WeixinUtil.httpRequest(url, "GET", null);
			responseMap.put("userJson", userJson);
			responseMap.put("cd", "1");
			return responseMap;
		}
	}
	
	
	/**
	 * 通过config接口注入权限验证配置
	 * @param request
	 * @param response
	 * @return 验证配置
	 * @throws Exception
	 */
	@RequestMapping(value = "/jsapi")
	@ResponseBody
	public Map<String, Object> jsApi(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String url = request.getParameter("url");
        String o = request.getParameter("o");
		String jsapi_ticket = JsapiTicketThread.getJsapiTicketStr(o);
		Map<String, Object> responseMap = JsApiSign.sign(jsapi_ticket, url, o);
		return responseMap;
	}
	
}
